package gbif.common.dal;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

@SuppressWarnings({"rawtypes","unchecked"})
public class EntityManager{

	
	private Map<String,IBaseDAO> entitiesDAOsMap;
	
	/**
	 * @return the entitiesDAOsMap
	 */
	public Map<String, IBaseDAO> getEntitiesDAOsMap() {
		return entitiesDAOsMap;
	}

	/**
	 * @param entitiesDAOsMap the entitiesDAOsMap to set
	 */
	public void setEntitiesDAOsMap(Map<String, IBaseDAO> entitiesDAOsMap) {
		this.entitiesDAOsMap = entitiesDAOsMap;
	}

	public <T> void save(T transientInstance) {
		this.entitiesDAOsMap.get(transientInstance.getClass().getName()).save(transientInstance);
		
	}
	
	public <T> void delete(T persistentInstance) {
		this.entitiesDAOsMap.get(persistentInstance.getClass().getName()).delete(persistentInstance);	
	}
	
	public <T extends Object> T findById(Serializable id, Class clazz) {
		return (T)this.entitiesDAOsMap.get(clazz.getClass().getName()).findById(id);
	}

	public <T> List<T> findByExample(T instance) {
		return this.entitiesDAOsMap.get(instance.getClass().getName()).findByExample(instance);
	}

	public <T> List<T> findByProperty(String propertyName, Object value, Class clazz) {
		return this.entitiesDAOsMap.get(clazz.getClass().getName()).findByProperty( propertyName,value);
	}

	public int bulkUpdateByProperty(String propertyName, Object value,	Operation operation, Class clazz) {
		return this.entitiesDAOsMap.get(clazz.getClass().getName()).bulkUpdateByProperty( propertyName,value,operation);
	}

	
	public int bulkUpdateByProperties(String[] propertiesNames,	Object[] values, Operation operation, Class clazz) {
		return this.entitiesDAOsMap.get(clazz.getClass().getName()).bulkUpdateByProperties(propertiesNames,	values,operation);
	}

	
	public <T> List<T> findAll(Class clazz) {
		return (List<T>)this.entitiesDAOsMap.get(clazz.getClass().getName()).findAll();
	}

	public <T> T merge(T detachedInstance) {
		return (T)this.entitiesDAOsMap.get(detachedInstance.getClass().getName()).merge(detachedInstance);
	}
	
	public void update(Object detachedInstance) {
		this.entitiesDAOsMap.get(detachedInstance.getClass().getName()).update(detachedInstance);	
	}

	public <T> void attachDirty(T instance) {
		this.entitiesDAOsMap.get(instance.getClass().getName()).update(instance);		
	}

	public <T> void attachClean(T instance) {
		this.entitiesDAOsMap.get(instance.getClass().getName()).update(instance);			
	}

}
